package com.sinog.front.controller.biz;

import com.sinog.core.model.UserDTO;
import com.sinog.core.util.JsonUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.Result;
import com.sinog.front.feign.biz.AdvanSearchService;
import com.sinog.front.service.user.UserFacade;
import com.sinog.front.util.FileUtil;
import com.sinog.front.util.SolrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @desc 数据统计分析 - 多维数据检索(高级检索) - 多维数据检索(高级检索) - FuzzySearchController
 * @author -
 * @date -
 */
@Slf4j
@RestController
public class FuzzySearchController {

    @Autowired
    private AdvanSearchService advanSearchService;
    @Autowired
    private UserFacade userService;
    @Value("${gkzx.azbj.solr.mh-yaz-solr-url}")
    private String mhyaz;
    @Value("${gkzx.azbj.solr.mh-azbj-solr-url}")
    private String mhazbj;
    @Value("${gkzx.azbj.solr.mh-jcab-solr-url}")
    private String mhjcab;
    @Value("${gkzx.azbj.solr.gj-yaz-solr-url}")
    private String gjyaz;
    @Value("${gkzx.azbj.solr.gj-azbj-solr-url}")
    private String gjazbj;
    @Value("${gkzx.azbj.solr.gj-jcab-solr-url}")
    private String gjjcab;

    /**
     * 数据统计分析 - 多维数据检索 - 多维数据检索 - 保存检索条件到tbsys_advansearch表里
     * @param request request
     * @return Result
     */
    @RequestMapping("/azbj/solrsearch/solr/saveFuzzySql")
    public Result saveFuzzySql(HttpServletRequest request) {
        Map<String,Object> map = new HashMap<>(16);
        UserDTO authentication = userService.getAuthentication();
        String account = authentication.getAccount();
        String nativepro = authentication.getDepartid();
        String sql = request.getParameter("sql");
        String type = request.getParameter("type");
        if(null != sql && !sql.trim().isEmpty()) {
            boolean containsCodeFlag = !sql.contains(Constants.StrFinalValue.NATIVEPRO)
                    && !sql.contains(Constants.StrFinalValue.NATIVECITY)
                    && !sql.contains(Constants.StrFinalValue.NATIVECOU);
            if(containsCodeFlag){
                sql += " AND ( ownpro:" + nativepro + " OR nativepro:" + nativepro + " )";
            }
        } else {
            sql += "nativepro:" + nativepro + " OR ownpro:" + nativepro;
        }
        map.put("createid",account);
        map.put("sqltext",sql);
        map.put("type",type);
        return advanSearchService.saveSqltext(map);
    }

    /**
     * 数据统计分析 - 多维数据检索 - 多维数据检索 - 模糊检索
     * @param request request
     * @return Map<String,Object>
     */
    @RequestMapping("/azbj/solrsearch/solr/fuzzySearch")
    @ResponseBody
    public Map<String,Object> fuzzySearch(HttpServletRequest request) {
        int start = Integer.parseInt(request.getParameter("start"));
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        String keywords = request.getParameter("keywords");
        String searchType = request.getParameter("searchType");
        String type = request.getParameter("type");
        String soleCore;
        if(Constants.NumberStr.NUM_STR_ONE.equals(searchType)) {
            soleCore = mhyaz;
        } else if(Constants.NumberStr.NUM_STR_TWO.equals(searchType)) {
            soleCore = mhazbj;
        } else {
            soleCore = mhjcab;
        }
        //创建HttpSolrClient
        HttpSolrClient client = new HttpSolrClient.Builder(soleCore).build();
        //创建SolrQuery
        SolrQuery solrQuery = new SolrQuery();
        //设置查询关键字
        if(StringUtils.isNotBlank(keywords)) {
            solrQuery.setQuery("keywords:" + keywords);
        } else {
            solrQuery.setQuery("*:*");
        }
        Map<String,Object> map = new HashMap<>(16);
        String createid = userService.getAuthentication().getAccount();
        map.put("createid",createid);
        map.put("type",type);
        map.put("start",start);
        map.put("pageSize",pageSize);
        String sqltext = advanSearchService.selectSqltext(map);
        //设置过滤条件
        if(StringUtils.isNotBlank(sqltext)) {
            solrQuery.addFilterQuery(sqltext);
        }
        //设置显示字段
        solrQuery.setFields("fl","prinum,pname,xb,idnum,pdanweiname,sfsj,hjdz,fileurl");
        Map<String,Object> queryMap = new HashMap<>(16);
        try {
            queryMap = SolrUtil.baseQueryBase(client,solrQuery,map);
        } catch(IOException | SolrServerException e) {
            log.error("发生异常:{}",e.getMessage());
        }
        return queryMap;
    }

    /**
     * 数据统计分析 - 高级检索 - 高级检索 - 保存检索条件到tbsys_advansearch表里
     * @param data data
     * @return Result
     */
    @PostMapping("/azbj/solrsearch/solr/saveSqltext")
    public Result saveSqltext(@RequestParam(required = false, defaultValue = "-1") String data) {
        UserDTO authentication = userService.getAuthentication();
        Result result = new Result();
        String sqlText;
        String nativepro = authentication.getDepartid();
        if(!StringUtils.equals(data,Constants.NumberStr.NUM_STR_FU_ONE)) {
            Map<String,Object> map = JsonUtil.toMap(data);
            sqlText = map.get("sqltext").toString();
            if(null != sqlText && !sqlText.trim().isEmpty() && !sqlText.isEmpty()) {
                if(!sqlText.contains(Constants.StrFinalValue.NATIVEPRO) && !sqlText.contains(Constants.StrFinalValue.NATIVECITY) && !sqlText.contains(Constants.StrFinalValue.NATIVECOU)) {
                    sqlText += " AND ( ownpro:" + nativepro + " OR nativepro:" + nativepro + " )";
                }
            } else {
                sqlText += "nativepro:" + nativepro + " OR ownpro:" + nativepro;
            }
            map.put("sqltext",sqlText);
            String createid = authentication.getAccount();
            map.put("createid",createid);
            return advanSearchService.saveSqltext(map);
        }
        return result;
    }

    /**
     * 数据统计分析 - 高级检索 - 高级检索 - 高级检索查询数据
     * @param data data
     * @return Map<String,Object>
     */
    @PostMapping("/azbj/solrsearch/solr/advanceSearch")
    public Map<String,Object> advanceSearch(@RequestParam(required = false, defaultValue = "-1") String data) {
        Map<String,Object> resultMap = new HashMap<>(16);
        if(!StringUtils.equals(data,Constants.NumberStr.NUM_STR_FU_ONE)) {
            Map<String,Object> dataMap = JsonUtil.toMap(data);
            if(null != dataMap) {
                String searchType = dataMap.get("searchType").toString();
                Integer start = (Integer)dataMap.get("start");
                Integer rows = (Integer)dataMap.get("pageSize");
                String type = dataMap.get("type").toString();
                String url = "";
                if(Constants.NumberStr.NUM_STR_ONE.equals(searchType)) {
                    url = gjyaz;
                } else if(Constants.NumberStr.NUM_STR_TWO.equals(searchType)) {
                    url = gjazbj;
                } else if(Constants.NumberStr.NUM_STR_THREE.equals(searchType)) {
                    url = gjjcab;
                }
                //创建HttpSolrClient
                HttpSolrClient client = new HttpSolrClient.Builder(url).build();
                //创建SolrQuery
                SolrQuery solrQuery = new SolrQuery();
                //设置查询关键字
                solrQuery.setQuery("*:*");
                Map<String,Object> map = new HashMap<>(16);
                String createid = userService.getAuthentication().getAccount();
                map.put("createid",createid);
                map.put("type",type);
                String sqltext = advanSearchService.selectSqltext(map);
                //设置过滤条件
                if(StringUtils.isNotBlank(sqltext)) {
                    solrQuery.addFilterQuery(sqltext);
                }
                //设置显示字段
                solrQuery.setFields("fl","prinum,pname,xb,idnum,pdanweiname,sfsj,hjdz,fileurl");
                solrQuery.setStart(start);
                solrQuery.setRows(rows);
                try {
                    resultMap = SolrUtil.baseQueryBase(client,solrQuery,null);
                } catch(IOException | SolrServerException e) {
                    log.error("发生异常:{}",e.getMessage());
                }
            }
        }
        return resultMap;
    }

    /**
     * 数据统计分析 - 高级检索 - 高级检索 - 读取图片
     * @param request request
     * @param response response
     */
    @RequestMapping("/azbj/search/queryImageData")
    @ResponseBody
    public void queryImageData(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String path = request.getParameter("url");
        PrintWriter writer;
        boolean pathBoolean = org.apache.commons.lang3.StringUtils.isBlank(path) || path.contains("/") || !path.contains(".");
        if(pathBoolean) {
            try {
                response.setContentType("text/html; charset=utf-8");
                writer = response.getWriter();
                writer.println("<script type=\"text/javascript\">alert('请求不合法');window.history.back(-1);</script>");
                writer.flush();
                return;
            } catch(IOException e) {
                log.error("请求不合法:{}",e.getMessage());
                return;
            }
        }
        String realPath = FileUtil.getUploadFilePath() + path;
        File file = new File(realPath);
        if(!file.exists()) {
            return;
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            is = new FileInputStream(file);
            byte[] bytes = new byte[is.available()];
            is.read(bytes);
            os = response.getOutputStream();
            String fileSuffix = path.substring(path.lastIndexOf('.') + 1);
            if(Constants.ImageType.IMAGE_PNG.equals(fileSuffix)) {
                response.setContentType("image/png");
            }
            if(Constants.ImageType.IMAGE_JPG.equals(fileSuffix) || Constants.ImageType.IMAGE_JPEG.equals(fileSuffix)) {
                response.setContentType("image/jpeg");
            }
            if(Constants.ImageType.IMAGE_BMP.equals(fileSuffix)) {
                response.setContentType("image/bmp");
            }
            os.write(bytes);
        } catch(FileNotFoundException e) {
            log.error("发生异常:",e);
        } finally {
            if(null != is) {
                is.close();
            }
            if(null != os) {
                os.close();
            }
        }
    }

    /**
     * 数据统计分析 - 高级检索 - 高级检索 - 服刑单位列表
     * @return List<Map < String,Object>>
     */
    @RequestMapping("/azbj/solrsearch/solr/getJailList")
    public List<Map<String,Object>> getJailList() {
        return advanSearchService.getJailList();
    }
}